import { getAuthCode } from "@/utils/dingding.js"
import { getAccessToken, getUserInfo, getUserOrCreate } from "@/api/base.js"
import * as setting from '@/config/setting.js'
import * as sCode from '@/config/statuxCode.js'
 
export const Login = () => {
  return new Promise((resolve, reject) => {
	  
	// uni.clearStorageSync()	// 删除删除
	
    const value = uni.getStorageSync(setting.authCodeMsg);
	if (value === sCode.code_200) {
		return
	}
	getAuthCode().catch(res => {
		if (res == sCode.code_400) {
			uni.reLaunch({ url: '/pages/common/illegality/illegality' }); // 关闭所有页面，跳转到对应路径的页面
		} else {
			getAccessToken().then(resA => {
				uni.setStorageSync(setting.accessToken, resA.data.access_token)
				if (resA.data.errcode != 0) {
					uni.reLaunch({ url: '/pages/common/illegality/illegality' }); // 关闭所有页面，跳转到对应路径的页面
				} else {
					getUserInfo(resA.data.access_token).then(resU => {
						const user_info_storage_data = {
							sys_level: resU.data.sys_level,
							name: resU.data.name,
							userid: resU.data.userid,
						}
						uni.setStorageSync(setting.userInfo, user_info_storage_data)
						// 请求后端，如果用户不存在则创建用户
						getUserOrCreate(user_info_storage_data)
						console.log('免登成功', res);
					})
				}
			})
		}
	})
  })
}


